package cz.zcu.fav.ratdroid.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import cz.zcu.fav.ratdroid.R;
import cz.zcu.fav.ratdroid.adapter.ObjectsArrayAdapter;
import cz.zcu.fav.ratdroid.bean.Object;
import cz.zcu.fav.ratdroid.bean.Objects;
/**
 * Abstract communication activity for all object list activities 
 * @author Lukas Gemela
 *
 */
public abstract class AbstractObjectsListActivitity extends SkeletonRestListActivity<Objects>
{
	private ObjectsArrayAdapter adapter;
	private static String LOADED_OBJECTS_KEY = "loaded.objects";
	private List<Object> loadedObjects = new ArrayList<Object>();
	private boolean recreated = false;

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.object_browser_layout);

		if (savedInstanceState != null)
		{
			recreated = true;
			loadedObjects = (List<Object>) savedInstanceState
					.getSerializable(LOADED_OBJECTS_KEY);
		} else
		{
			loadedObjects = provideData();
		}
		adapter = new ObjectsArrayAdapter(this, R.layout.object_row,
				loadedObjects);
		setListAdapter(adapter);
	}

	/**
	 * meant do be implemented. defines how to serve data to model.
	 * @return
	 */
	protected abstract List<Object> provideData();

	public List<Object> getLoadedObjects()
	{
		return loadedObjects;
	}

	public boolean isRecreated()
	{
		return recreated;
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState)
	{
		// Save the user's current game state
		savedInstanceState.putSerializable(LOADED_OBJECTS_KEY,
				(Serializable) loadedObjects);
		// Always call the superclass so it can save the view hierarchy state
		super.onSaveInstanceState(savedInstanceState);
	}

	public void notifyDataLoaded(Objects data)
	{
		super.notifyDataLoaded(data);
		adapter.notifyDataSetChanged();
		if (data != null)
		{
			adapter.clear();
			adapter.addAll(data.getObjects());
			adapter.notifyDataSetChanged();
		}

	}

}
